/**
 * 
 */
package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author jbrasca
 * date: Aug 9, 2011
 */
public class MailTemplate {
	private Connection connection;
	private String country;
	private String name;
	/**
	 * 
	 */
	public MailTemplate() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3307/test","root", "root");			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}

	public MailTemplate(String country, String  name){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3307/test","root", "root");			
			if(country!= null){
				this.country = country.toLowerCase();
			}
			this.name = name;
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public String getMailContent(){		
		String mailContent = new String();
		
		try {
			Statement s = connection.createStatement();
			ResultSet rs = s.executeQuery ("select propertyValue from properties where property = \""+getCountry()+"MailContent\"" );
			if(rs.next()){
				mailContent =  rs.getString(1);
			}else{
				rs =  s.executeQuery("select propertyValue from properties where property = \"defaultMailContent\" ");
				if(rs.next()){
					mailContent = rs.getString(1);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		mailContent = replaceTemplateVariables(mailContent);
		
		return mailContent;
	}
	
	/**
	 * @param mailContent
	 * @return
	 */
	private String replaceTemplateVariables(String mailContent) {

		if(getName()!=null){
			mailContent = mailContent.replaceAll("<NAME>" , getName());
		}
		
		return mailContent;
	}

	public String getMailSubject(){
		String mailSubject=  new String();
		try {
			Statement s = connection.createStatement();
			ResultSet rs = s.executeQuery ("select propertyValue from properties where property = \""+getCountry()+"MailSubject\"" );
			if(rs.next()){
				mailSubject =  rs.getString(1);	
			}else{
				rs =  s.executeQuery("select propertyValue from properties where property = \"defaultMailSubject\" ");
				if(rs.next()){
					mailSubject = rs.getString(1);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return mailSubject;
		
	}

	private String getCountry() {
		return country;
	}

	private String getName() {
		return name;
	}
	
	
}
